<?php
/**
 * Desc: Service模板
 * User: zdb
 * Date: 2023/6/5
 * Time: 11:22
 */

namespace app\api\service\develop;
use app\util\CommonUtil;
use think\facade\Db;

class DatagridCustomService
{

    private $primaryTable;

    public function __construct()
    {
        $this->primaryTable = "yj_datagrid_custom";
    }

    public function findRowById($id)
    {
        return Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->find();
    }

    public function findRowByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        return Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->strict(false)
            ->find();
    }

    public function getListByManyId($arrId)
    {
        $list = Db::table($this->primaryTable)->alias('a')
            ->whereIn('id', $arrId)
            ->select()
            ->toArray();
        return $list;
    }

    public function assembleFilterCondition($data)
    {
        $condition = ['a.status > 0'];

        if (!empty($data['title'])) {
            $condition[] = "title like '%" . $data['title'] . "%'";
        }

        if (!empty($data['datagrid_code'])) {
            $condition[] = "a.datagrid_code = '" . $data['datagrid_code'] . "'";
        }

        return empty($condition) ? "" : implode(" AND ", $condition);
    }

    public function getListNoPage($data = [])
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->select()
            ->toArray();
        return $res;
    }

    public function getListWithPage($data, $pageIndex = 1, $pageSize = 30)
    {
        $offset = ($pageIndex - 1) * $pageSize;
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->leftJoin("yj_menu mt", "mt.id = a.menu_id")
            ->leftJoin("yj_menu ms", "ms.id = mt.parent_menu_id")
            ->where($condition)
            ->field("a.*, mt.menu_name_cn as third_menu_name, ms.menu_name_cn as second_menu_name")
            ->limit($offset, $pageSize)
            ->order('a.menu_id asc, a.id desc')
            ->select();
        return $res;
    }

    public function getTotalNum($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $num = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->count();
        return $num;
    }

    public function createRow($data)
    {
        $data['status'] = isset($data['status']) ? $data['status']:1;
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->insert($data, true);
        return $res;
    }

    public function createManyRow($data)
    {
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->duplicate($data)
            ->insertAll($data, true);
        return $res;
    }

    public function updateRowById($id, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByData($condition, $data)
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByManyId($arrId, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeRowById($id)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByManyId($arrId)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    /**
     * Desc: 新增定制页面
     * 同时生成页面、纵列、请求、功能按钮4个部分的数据
     * @param $data
     * @return mixed
     * Datetime: 2024/9/14 15:04 by zdb
     */
    public function addDatagridCustom($data)
    {
        $model = Db::table($this->primaryTable);
        try{
            $model->startTrans();
            $pageData = array(
                'table_id' => $data['table_id'],
                'menu_id' => $data['menu_id'],
                'table_name' => $data['table_name'],
                'datagrid_code' => $data['datagrid_code'],
                'datagrid_name' => $data['datagrid_name'],
            );
            $keyword = str_replace('yj_', '', $data['table_name']);
            $upperCamel = CommonUtil::covertUnderlineToUpperCamel($keyword);
            $newPageId = $model->insert($pageData, true);
            $arrDataType = array('date', 'datetime');
            if($newPageId){
                $serviceDatagridColumn = new DatagridColumnService();
                $serviceTableField = new TableFieldService();
                $tableFieldList = $serviceTableField->getListNoPage(array('table_id' => $data['table_id']));
                foreach($tableFieldList as $fieldItem){
                    $newColumn = array();
                    $newColumn['datagrid_id'] = $newPageId;
                    $newColumn['table_field_id'] = $fieldItem['id'];
                    $newColumn['column_name'] = $fieldItem['field_name'];
                    $newColumn['column_title'] = $fieldItem['field_title'];
                    if(in_array($fieldItem['data_type'], $arrDataType)){
                        $newColumn['element_type'] = $fieldItem['data_type'];
                    }else{
                        $newColumn['element_type'] = 'text';
                    }
                    $newColumn['sort'] = $fieldItem['sort'];
                    $newColumnId = $serviceDatagridColumn->createRow($newColumn);
                    if(!$newColumnId){
                        $model->rollback();
                        return false;
                    }
                }

                $arrPagePath = array(
                    'add' => '/admin/'.$upperCamel.'/pageAdd',
                    'edit' => '/admin/'.$upperCamel.'/pageEdit',
                );

                $arrApiPath = array(
                    'add' => '/api/'.$upperCamel.'/add'.$upperCamel,
                    'edit' => '/api/'.$upperCamel.'/edit'.$upperCamel,
                    'delete' => '/api/'.$upperCamel.'/delete'.$upperCamel,
                    'refresh' => '/api/'.$upperCamel.'/get'.$upperCamel.'List',
                );

                //最后生成功能按钮
                $serviceDatagridToolbar = new DatagridToolbarService();
                foreach($serviceDatagridToolbar::ARR_TOOLBAR_INFO as $enText => $barInfo){
                    $pagePath = isset($arrPagePath[$enText]) ? $arrPagePath[$enText]:'';
                    $apiPath = isset($arrApiPath[$enText]) ? $arrApiPath[$enText]:'';
                    $isNeedCheck = $barInfo['is_need_check'] ?? 1;
                    $newToolbarData = array(
                        'datagrid_id'       => $newPageId,
                        'button_type'   => $enText,
                        'button_text'   => $barInfo['button_text'],
                        'button_icon'   => $barInfo['button_icon'],
                        'button_class'   => $barInfo['button_class'],
                        'request_page_path' => $pagePath,
                        'request_api_path' => $apiPath,
                        'is_need_check'  => $isNeedCheck

                    );
                    $newToolbarId = $serviceDatagridToolbar->createRow($newToolbarData);
                    if(!$newToolbarId){
                        $model->rollback();
                        return false;
                    }
                }
                $model->commit();
                return true;
            }else{
                $model->rollback();
                return false;
            }
        }catch(\Exception $e){
            $model->rollback();
            $message = CommonUtil::getExceptionMessage($e);
            CommonUtil::addErrorLog("DatagridCustomService", "addDatagridCustom", $message);
            return false;
        }
    }
}